package com.pay.good.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pay.common.utils.Result;
import com.pay.good.pojo.TGoods;
import com.pay.good.service.TGoodsService;
import com.pay.good.mapper.TGoodsMapper;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
* @author 28242
* @description 针对表【t_goods(商品表)】的数据库操作Service实现
* @createDate 2025-08-08 15:00:59
*/
@Service
@Slf4j
public class TGoodsServiceImpl extends ServiceImpl<TGoodsMapper, TGoods>
    implements TGoodsService{

    @Autowired
    private TGoodsMapper tGoodsMapper;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @PostConstruct
    public void init(){
        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(TGoods.class);
        if (!indexOps.exists()){
            indexOps.create();
            Document mapping = indexOps.createMapping();
            indexOps.putMapping(mapping);
        }
        log.info("初始化索引成功");
    }


    @Override
    public Result syncGoodsToEs() {

       List<TGoods> tGoodsList = tGoodsMapper.selectList(null);

        for (TGoods tGoods : tGoodsList) {
            TGoods tGoods1 = BeanUtil.toBean(tGoods, TGoods.class);
            elasticsearchRestTemplate.save(tGoods1);
        }
        log.info("同步商品到es成功");
     return Result.ok();
    }


}




